package proj.pt.web;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import proj.pt.model.User;

public class LoginController extends CustomSimpleFormController{
	
	protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception {
		request.getSession().invalidate();
		return super.referenceData(request, command, errors);
	} //end referenceData
	
	protected boolean isFormChangeRequest(HttpServletRequest request, Object command) {
		return false;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
            HttpServletResponse response,
            Object command,
            BindException errors)
     throws Exception {
		
		String username = WebUtils.getStringParameter(request, "username");
		String password = WebUtils.getStringParameter(request, "password");
		boolean successView = false;
		
		if(StringUtils.hasLength(username) && StringUtils.hasLength(password)){
			User user = getLogicProcessor().validateLogin(username, password);
			if(user != null){
				request.getSession().setAttribute("LOGIN_USER_NAME", user.getName());
				request.getSession().setAttribute("LOGIN_USER_ROLE", user.getRoleId());
				request.getSession().setAttribute("LOGIN_USER", user);
				successView = true;
			} else {
				request.getSession().invalidate();
			} //end else
		} //end if
				
		ModelAndView  mav = new ModelAndView();
		if(successView){
			mav.setView(new RedirectView(getSuccessURI()));
		} else {
			mav.setView(new RedirectView(getFailureURI()));
		} //end else
		return mav;
	} //end onSubmit	
}
